#! /usr/bin/env python3

""" CLI command completion helper

    nipap_helper.py is used to provide tab completion capabilities of nipap
    commands to for example bash.
"""

import configparser
import os
import shlex
import sys
from nipap_cli.command import Command, InvalidCommand
from nipap_cli import nipap_cli
from pynipap import NipapError


__author__      = "Kristian Larsson, Lukas Garberg"
__author_email__ = "kll@tele2.net, lukas@spritelink.net"
__license__     = "MIT"
__status__      = "Development"
__url__         = "http://SpriteLink.github.io/NIPAP/"


if __name__ == '__main__':

    # make sure nipaprc exists and has correct permissions
    userrcfile = os.path.expanduser('~/.nipaprc')

    # read configuration
    cfg = configparser.ConfigParser({'prefix_list_columns': ''})
    cfg.read(userrcfile)
    nipap_cli.cfg = cfg

    # setup our configuration
    nipap_cli.setup_connection()

    comp = []

    # tab completion haxx. it seems that sometimes the offset is different and
    # so we try to search for 'nipap' to find the correct to start parsing
    # command line stuff at. Since nipap could be called with a path, like
    # './nipap', it won't always match and then we assume an offset of 2, which
    # is correct in the majority of cases
    try:
        offset = 1 + sys.argv.index('nipap')
    except:
        offset = 2

    # let shlex handle escaped whitespaces and similar
    args = []
    for arg in sys.argv[offset::]:
        try:
            if arg != '': arg = shlex.split(arg)[0]
        except:
            sys.exit()
        args.append(arg)

    try:
        cmd = Command(nipap_cli.cmds, args)
        comp = sorted(cmd.complete())
    except Exception:
        # handle errors silently
        pass

    for val in comp:
        print(val)
